package com.server.service.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.server.common.chart.ChartSeries;
import com.server.common.chart.ColumnVectorV2;
import com.server.date.DateType;
import com.server.date.DateUtil;
import com.server.service.ICommonDataService;
import com.server.service.IMonthStatisticService;
import com.server.web.DataVector;
import com.server.web.RequestInput;

@Service("MonthStatisticService")
public class MonthStatisticService implements IMonthStatisticService {
	
	private static final String TABLE_NAME = "reward.reward";
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private ICommonDataService commonDataService;
	
	 /**
	 * 获取已返费的月份区间
	 * @param cardId
	 * @return
	 * @author ServerZhang
	 * @date 2017年3月13日
	 */
	@Override
	public List<Map<String,Object>> getPeriod(String cardId){
		String sql = "select * from %s where CardID='%s' and State=2 and RewardTime is not null order by RewardTime asc";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(String.format(sql, TABLE_NAME,cardId));
		if (list.size() < 1) {
			return list;
		}
		Map<String, Object> map1 = list.get(0);
		Map<String, Object> map2 = list.get(list.size()-1);
		Date startDate = (Date)map1.get("RewardTime");
		Date endDate = (Date)map2.get("RewardTime");
		
		List<Map<String, Object>> monthPeriod = DateUtil.getMonthPeriod(startDate, endDate);
		return monthPeriod;
	}
	@Override
	public ColumnVectorV2 getStatictics(String cardId, 
			String startPeriod, String endPeriod) {
		String[] start = startPeriod.split("-");
		String[] end = endPeriod.split("-");
		
		Calendar instance = Calendar.getInstance();
		instance.set(Integer.parseInt(start[0]), Integer.parseInt(start[1])-1, 1,0,0);
		Date startTime = instance.getTime();
		instance.set(Integer.parseInt(end[0]), Integer.parseInt(end[1]), 1,0,0);
		Date endTime = instance.getTime();
		String endStr = DateUtil.getDateStr(endTime, DateType.YYYY_MM_DD);
		
		String sql = "select * from %s where CardID='%s' and RewardTime>='%s' and RewardTime<='%s' and state=2";
		String format = String.format(sql, TABLE_NAME,cardId,startPeriod,endStr);
		List<Map<String, Object>> list = jdbcTemplate.queryForList(format);
		
		ColumnVectorV2 dataVector = new ColumnVectorV2();
		
		Map<String, Map<String, Float>> iniDatas = this.iniDatas(startPeriod, endPeriod);
		
		Iterator<Map<String, Object>> iterator = list.iterator();
		
		while(iterator.hasNext()){
			Map<String, Object> row = iterator.next();
			Object timeObj = row.get("RewardTime");
			if (timeObj != null) {
				Float amount = (Float)row.get("Amount");
				String timeSub = timeObj.toString().substring(0, 7);
				Map<String, Float> map = iniDatas.get(timeSub);
				if (map == null) {
					map = new HashMap<String, Float>();
					map.put("normal", amount);
				}else {
					Float count = map.get("normal");
					map.put("normal", count+amount);
				}
				iniDatas.put(timeSub, map);
			}
		}
		
		int size = iniDatas.size();
		String[] xAxisData = new String[size];
		Double[] userArray = new Double[size];
		
		Set<String> keySet = iniDatas.keySet();
		int i = 0;
		for(String key : keySet){
			Map<String, Float> map = iniDatas.get(key);
			xAxisData[i] = key;
			userArray[i] = (double)map.get("normal");
			i++;
		}
		
		dataVector.setxAxisData(xAxisData);
		dataVector.addSeries(new ChartSeries("本月收入",userArray));
		
		return dataVector;
	}
	private Map<String,Map<String, Float>> iniDatas(String startStr, String endStr){
		Map<String, Map<String, Float>> returnMap = new LinkedHashMap<String, Map<String,Float>>();
		int year = Integer.parseInt(startStr.substring(0, 4));
		int month = Integer.parseInt(startStr.substring(5, 7));
		
		int endYear = Integer.parseInt(endStr.substring(0, 4));
		int endMonth = Integer.parseInt(endStr.substring(5, 7));
		
		for(int i=year; i<=endYear; i++){
			int start = 1;
			int end = 12;
			if (i == year) {
				start = month;
			}
			if (i == endYear) {
				end = endMonth;
			}
			for (int j = start; j <= end; j++) {
				Map<String, Float> map = new HashMap<String, Float>();
				map.put("normal", 0.0F);
				String tempJ = j > 10 ? j+"" : "0"+j; 
				returnMap.put(i+"-"+tempJ, map);
			}
		}
		return returnMap;
	}
	 /**
	 * 月份区间内的返费详细
	 * @param requestInput
	 * @param cardId
	 * @param startPeriod
	 * @param endPeriod
	 * @return
	 * @author ServerZhang
	 * @date 2017年3月13日
	 */
	@Override
	public DataVector<Map<String, Object>> getList(RequestInput requestInput, 
			String cardId,String startPeriod,String endPeriod){
		StringBuffer sBuffer = new StringBuffer();
		sBuffer.append("CardID='").append(cardId)
			.append("' and State=2");
		
		Calendar instance = Calendar.getInstance();
		if (startPeriod != null) {
			String[] start = startPeriod.split("-");
			instance.set(Integer.parseInt(start[0]), Integer.parseInt(start[1])-1, 1,0,0);
			Date startTime = instance.getTime();
			String startStr = DateUtil.getDateStr(startTime, DateType.YYYY_MM_DD);
			sBuffer.append(" and RewardTime>='").append(startStr).append("'");
		}
		if (endPeriod != null) {
			String[] end = endPeriod.split("-");
			instance.set(Integer.parseInt(end[0]), Integer.parseInt(end[1]), 1,0,0);
			Date endTime = instance.getTime();
			String endStr = DateUtil.getDateStr(endTime, DateType.YYYY_MM_DD);
			sBuffer.append(" and RewardTime<='").append(endStr).append("'");
		}
		
		String sortStr = "RewardTime desc";
		return commonDataService.getListData(TABLE_NAME, sBuffer.toString(), sortStr, requestInput);
	}
}
